import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // cartList: [],
    cartList: [
      {
        id: '772',
        image:
          'https://s5.mogucdn.com/mlcdn/c45406/200503_891e3h2hb12ej70jh295kcck7676d_640x960.jpg',
        title: '时尚大码女装拼接撞色字母印花大口袋宽松上衣夏装潮新款短袖T恤',
        desc: '描述文字',
        price: '49.90',
        count: 1,
        isChecked: false,
      },
      {
        id: '773',
        image:
          'https://s5.mogucdn.com/mlcdn/c45406/200503_891e3h2hb12ej70jh295kcck7676d_640x960.jpg',
        title: '时尚大码女装拼接撞色字母印花大口袋宽松上衣夏装潮新款短袖T恤',
        desc: '描述文字',
        price: '49.90',
        count: 1,
        isChecked: true,
      },
      {
        id: '774',
        image:
          'https://s5.mogucdn.com/mlcdn/c45406/200503_891e3h2hb12ej70jh295kcck7676d_640x960.jpg',
        title: '时尚大码女装拼接撞色字母印花大口袋宽松上衣夏装潮新款短袖T恤',
        desc: '描述文字',
        price: '49.90',
        count: 1,
        isChecked: false,
      },
      {
        id: '775',
        image:
          'https://s5.mogucdn.com/mlcdn/c45406/200503_891e3h2hb12ej70jh295kcck7676d_640x960.jpg',
        title: '时尚大码女装拼接撞色字母印花大口袋宽松上衣夏装潮新款短袖T恤',
        desc: '描述文字',
        price: '49.90',
        count: 1,
        isChecked: false,
      },
      {
        id: '776',
        image:
          'https://s5.mogucdn.com/mlcdn/c45406/200503_891e3h2hb12ej70jh295kcck7676d_640x960.jpg',
        title: '时尚大码女装拼接撞色字母印花大口袋宽松上衣夏装潮新款短袖T恤',
        desc: '描述文字',
        price: '49.90',
        count: 1,
        isChecked: false,
      },
    ],
  },
  getters: {
    cartListLength(state) {
      return state.cartList.length
    },
    cartListChecked(state) {
      const listChecked = state.cartList.filter((item) => {
        return item.isChecked
      })

      return listChecked
    },
  },
  mutations: {
    cartListAddCount(state, goods) {
      goods.count++
    },
    cartListAddItem(state, goods) {
      state.cartList.push(goods)
    },
    changeCartListChecked(state, goods) {
      let tempGoods = state.cartList.find((item) => item.id === goods.id)
      tempGoods.isChecked = goods.isChecked
    },
    changeCartListAllStatus(state, flag) {
      state.cartList.forEach((item) => {
        item.isChecked = flag
      })
    },
  },
  actions: {
    addCartList(context, goods) {
      return new Promise((resolve, reject) => {
        let oldGoods = context.state.cartList.find(
          (item) => item.id === goods.id
        )
        // 由于模拟数据只有一个商品，测试为了展示多个商品，则让他每次都是新增而不是数量加一
        oldGoods = false
        if (oldGoods) {
          context.commit('cartListAddCount', oldGoods)
          resolve({
            code: 0,
            msg: '添加商品成功（新商品）',
          })
        } else {
          context.commit('cartListAddItem', goods)
          resolve({
            code: 0,
            msg: '添加商品成功（数量+1）',
          })
        }
      })
    },
  },
  modules: {},
})
